package com.example.newsmanager.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.newsmanager.common.Result;
import com.example.newsmanager.service.NewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/file")
public class FileUploadController {

    @Value("${files.upload.path}") // 从配置文件中读取上传文件保存路径
    private String uploadPath;
    private NewsService newsService;
    @PostMapping("/upload")
    public Result<?> handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("请选择要上传的文件");
        }

        try {
            // 生成一个唯一的文件名
            String uniqueFileName = UUID.randomUUID().toString() + "_" + StringUtils.cleanPath(file.getOriginalFilename());

            // 将文件保存到指定路径
            Path targetLocation = Paths.get(uploadPath).resolve(uniqueFileName);
            File targetFile = targetLocation.toFile();
            file.transferTo(targetFile);

            // 构建文件的URL
            String fileUrl = "http://114.55.129.172:8080/upload/" + uniqueFileName; // 替换为你的服务器域名和路径
            log.info(fileUrl);
            return Result.success(fileUrl,"上传图片成功");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("文件上传失败");
        }
    }
}